
import { queryBtnList } from '@/api/permissions'
import { delTabConf, updateSort } from '@/api/tabConf'
export default {
  props: {
    defineTabData: {
      // 自定义导航数据: 若为首页导航(新导航配置)，id为固定从getHomePageTabDefine获取
      type: Object,
      default: () => {}
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableSelected: [], // 当前所选中表格行数据
      otherFilters: [], // 表格额外查询条件
      tabDefineData: '', // 当前自定义导航数据
      sorting: false,
      showEdit: false,
      buttons: [],
      detailData: {}
    }
  },
  created() {
    if (this.defineTabData && this.defineTabData.id) {
      this.tabDefineData = { ...this.defineTabData, ...{}}
      this.otherFilters = [
        { id: 'v2TabDefineId', property: 'v2TabDefineId', operator: '=', value: this.tabDefineData.id }
      ]
    }
    if (this.readonly === true) {
      const setting = this.tableConfig.setting.filter(v => !['sort', 'opetate'].includes(v.prop))
      this.$set(this.tableConfig, 'setting', setting)
      this.$set(this.tableConfig, 'hideFuncBar', true)
    }
    this.getBtnsList()
  },
  computed: {
    tabDefineId() {
      return this.tabDefineData && this.tabDefineData.id || ''
    },
    tabLevelName() {
      const { showLevel } = this.tabDefineData
      const obj = {
        '1': '一级',
        '2': '二级',
        '3': '三级',
        '4': '四级'
      }
      return obj[`${showLevel}`] || ''
    }
  },

  methods: {
    getBtnsList() {
      const menuCode = this.$route.query.menuCode
      if (!menuCode) return
      const buttonGroupCode = 'inRow'
      queryBtnList({ menuCode, buttonGroupCode }).then(res => {
        // res.data.groovyList
        this.buttons = (res.data && res.data.groovyList) || []
      })
    },
    hasPermission(code) {
      if (!this.isProduction) return true
      return this.buttons.filter(v => v.buttonCode === code).length > 0
    },
    fitlerPlatformName(val) {
      if (!val) return ''
      const arr = val.split(',')
      const name = []
      if (arr.includes('mobile')) {
        name.push('移动端')
      }
      if (arr.includes('pc')) {
        name.push('PC端')
      }
      if (arr.includes('pad')) {
        name.push('PAD')
      }
      return name.join(',')
    },
    btnOperate(code) {
      switch (code) {
        case 'add':
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'del':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleDelete(this.tableSelected[0])
          break
      }
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
    },
    isLastNode(levelType) {
      // 是否末级
      const { type, showLevel } = this.tabDefineData
      if ([0, '0'].includes(type)) {
        // 首页导航(新导航)只允许一二级可新增子级
        return !['FIRST', 'SECOND'].includes(levelType)
      }
      // 是否末级:导航层级为1级的，不允许新增子级
      if (['1', 1].includes(showLevel)) {
        return true
      } else if (['2', 2].includes(showLevel)) {
        return levelType !== 'FIRST'
      } else if (['3', 3].includes(showLevel)) {
        return !['FIRST', 'SECOND'].includes(levelType)
      } else if (['4', 4].includes(showLevel)) {
        return !['FIRST', 'SECOND', 'THIRD'].includes(levelType)
      }
      return true
    },
    // 新增/编辑基础信息
    handleEdit(row) {
      if (row && row.id) {
        const showPlatform = row.showPlatform ? row.showPlatform.split(',') : []
        this.detailData = { ...row, ...{ showPlatform }}
      } else {
        this.detailData = {
          levelType: 'FIRST',
          parent: '0'
        }
      }
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    handleAddChild(row) {
      const childLevelTypes = {
        'FIRST': 'SECOND',
        'SECOND': 'THIRD',
        'THIRD': 'FOURTH'
      }
      this.detailData = {
        parent: row.id,
        levelType: childLevelTypes[row.levelType]
      }
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    // 删除
    handleDelete(row) {
      const { id, tabName } = row
      this.$confirm(`确定删除【${tabName}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTabConf(id).then(res => {
          if (res.success === 1) {
            this.$message.success('删除成功')
            this.refreshTable()
          }
        })
      })
    },
    /**
   * 排序
   * @param {Object} row 排序行
   * @param {string} type 移动类型(bottom 置底 ，top 置顶 ， moveDown 下移 ，  moveUp 上移)
  */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      const params = {
        id: row.id,
        type
      }
      this.sorting = true
      updateSort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    },

    gotoContent(row) {
      const { gotoType, categoryDTOList, filterId, gotoValue, gotoName } = row
      const obj = {
        'HELP_CENTER': '帮助中心',
        'HELP_CENTER_DETAIL': '帮助中心详情',
        'CUSTOM_PAGE': '自定义页面',
        'GOODS_CENTER_DETAIL': '商品详情',
        'ATLAS': '画册',
        'APPLY_PAGE': '应用页面',
        'OUTSIDE_LINK': '外部链接',
        'GOODS_CENTER_CATEGORY': '商品中心类目',
        'GOODS_CATE': '商品分类',
        'CUSTOMIZED_NEW_PRODUCT_SERIES': '定制新品系列',
        'DEFINE_TAB': '自定义导航'
      }
      let result = obj[gotoType] || ''
      if (gotoType === 'OUTSIDE_LINK') {
        result += '：' + gotoValue
      } else {
        if (gotoName) {
          result += '：' + gotoName
        }
      }
      return result
    }
  }
}
